package com.kongwg.java1;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author kongwg
 * @create 2020-12-23 18:27
 */
public class UDPTest {

    @Test
    public void sender() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            String str = "我是UDP";
            byte[] data = str.getBytes();
            DatagramPacket packet = new DatagramPacket(data, 0, data.length, InetAddress.getLocalHost(), 9900);

            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {

                socket.close();
            }
        }


    }

    @Test
    public void receiver() throws Exception{

        DatagramSocket socket = new DatagramSocket(9900);

        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));
        socket.close();

    }
}
